package cn.snmp.mutual.uk.stack;

import java.io.*;

public class AsnUnsInteger64 extends AsnObject {
    private static final String version_id = "@(#)$Id: AsnUnsInteger64.java,v 3.16 2009/03/05 13:11:33 birgita Exp $ Copyright Westhawk Ltd";
    protected long value;

    public AsnUnsInteger64(final long v) {
        this.value = v;
        this.type = 70;
    }

    public AsnUnsInteger64(final InputStream in, final int len) throws IOException {
        final byte[] data = new byte[len];
        if (len != in.read(data, 0, len)) {
            throw new IOException("AsnUnsInteger64(): Not enough data");
        }
        this.value = this.bytesToLong(data);
    }

    public long getValue() {
        return this.value;
    }

    @Override
    public String toString() {
        return String.valueOf(this.value);
    }

    @Override
    int size() {
        int empty = 0;
        int sign = 0;
        if (this.value < 0L) {
            empty = 255;
            sign = 128;
        }
        int count;
        for (count = 56; count > 0 && (this.value >> count & 0xFFL) == empty; count -= 8) {
        }
        if ((this.value >> count & 0x80L) != sign) {
            count += 8;
        }
        return (count >> 3) + 1;
    }

    @Override
    void write(final OutputStream out, final int pos) throws IOException {
        int empty = 0;
        int sign = 0;
        if (this.value < 0L) {
            empty = 255;
            sign = 128;
        }
        int count;
        for (count = 56; count > 0 && (this.value >> count & 0xFFL) == empty; count -= 8) {
        }
        if ((this.value >> count & 0x80L) != sign) {
            count += 8;
        }
        this.AsnBuildHeader(out, (byte) 70, (count >> 3) + 1);
        if (debug > 10) {
            System.out.println("\tAsnUnsInteger64(): value = " + this.value + ", pos = " + pos);
        }
        while (count >= 0) {
            out.write((byte) (this.value >> count & 0xFFL));
            count -= 8;
        }
    }

    protected long bytesToLong(final byte[] data) throws IOException {
        final DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));
        long val = 0L;
        for (int size = data.length, n = 0; n < size; ++n) {
            val = (val << 8) + dis.readUnsignedByte();
        }
        return val;
    }

    @Override
    public boolean equals(final Object obj) {
        return obj instanceof AsnUnsInteger64 && this.value == ((AsnUnsInteger64) obj).value;
    }

    @Override
    public int hashCode() {
        return (int) (this.value ^ this.value >>> 32);
    }
}
